<template>
    <!-- 往来单位-编辑 -->
    <div class="e-form">
        <div class="tabs warningTabs" v-if="Object.keys(formData).length != 0">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <!-- 基本信息 -->
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <el-tab-pane
                    label="附件信息"
                    name="accessory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <div>
                    <!-- 基本信息 -->
                    <div id="baseInfoCon" class="con">
                        <div class="e-form">
                            <div class="tabs">
                                <div class="tabs-title" id="baseInfo">
                                    基本信息
                                </div>
                                <div style="width: 100%" class="form">
                                    <el-form
                                        :model="formData"
                                        ref="formData"
                                        :rules="rules"
                                        label-width="150px"
                                    >
                                     <BillTop title="往来单位编辑" @cancel="handleClose"></BillTop>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="单位类型"
                                                    prop="businessUnitTypeValue"
                                                >
                                                    <el-select
                                                        v-model="
                                                            formData.businessUnitTypeValue
                                                        "
                                                        placeholder="请选择"
                                                        @change="
                                                            businessUnitTypeChange
                                                        "
                                                        :disabled="isDisable"
                                                    >
                                                        <el-option
                                                            v-for="item in unitList"
                                                            :key="item.kvId"
                                                            :label="item.kvKey"
                                                            :value="
                                                                item.kvValue
                                                            "
                                                        >
                                                        </el-option>
                                                    </el-select>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="业务类型"
                                                    prop="businessTypeValue"
                                                >
                                                    <el-select
                                                        :disabled="
                                                            formData.businessUnitTypeValue ==
                                                            ''||isDisable
                                                        "
                                                        v-model="
                                                            formData.businessTypeValue
                                                        "
                                                        placeholder="请选择"
                                                        @change="
                                                            businessTypeKeyChange
                                                        "
                                                    >
                                                        <el-option
                                                            v-for="item in businessList"
                                                            :key="item.kvId"
                                                            :label="item.kvKey"
                                                            :disabled="
                                                                item.disabled
                                                            "
                                                            :value="
                                                                item.kvValue
                                                            "
                                                        >
                                                        </el-option>
                                                    </el-select>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    v-if="
                                                        formData.businessUnitTypeValue ==
                                                        '0'
                                                    "
                                                    label="身份证号码"
                                                     prop="creditCode"
                                                       key="1"
                                                >
                                                    <el-input
                                                        :disabled="
                                                            formData.businessTypeValue ==
                                                            ''||isDisable
                                                        "
                                                        placeholder="请填写"
                                                        v-model="
                                                            formData.creditCode
                                                        "
                                                        maxlength="18"
                                                    ></el-input>
                                                </el-form-item>
                                                <el-form-item
                                                    v-else-if="
                                                        formData.businessUnitTypeValue ==
                                                        '6'
                                                    "
                                                    label="机构编码"
                                                      key="2"
                                                >
                                                    <el-input
                                                        disabled
                                                        v-model="
                                                            formData.creditCode
                                                        "
                                                        maxlength="18"
                                                    ></el-input>
                                                </el-form-item>
                                                <el-form-item
                                                    v-else
                                                    label="统一社会信用代码"
                                                    prop="creditCode"
                                                      key="3"
                                                >
                                                    <el-input
                                                        :disabled="
                                                            formData.businessTypeValue ==
                                                            ''||isDisable
                                                        "
                                                        placeholder="请填写"
                                                        v-model="
                                                            formData.creditCode
                                                        "
                                                        maxlength="18"
                                                    ></el-input>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="单位名称"
                                                    prop="businessUnitName"

                                                >
                                                    <el-input
                                                        :placeholder="
                                                            formData.businessUnitTypeValue ==
                                                            '6'
                                                                ? '请选择单位名称'
                                                                : '请填写单位名称'
                                                        "
                                                        v-model="
                                                            formData.businessUnitName
                                                        "
                                                    :disabled="
                                                            formData.businessUnitTypeValue ==
                                                            '6'
                                                        "
                                                    >
                                                        <i
                                                            v-if="
                                                                formData.businessUnitTypeValue ==
                                                                '6'
                                                            "
                                                            slot="suffix"

                                                            class="
                                                                el-icon-document-copy
                                                            "
                                                            @click="onSelect"
                                                        ></i>
                                                    </el-input>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="联系人">
                                                    <el-input
                                                        placeholder="请填写"
                                                        v-model="
                                                            formData.contactName
                                                        "
                                                    ></el-input>
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="联系电话">
                                                    <el-input
                                                        placeholder="请填写"
                                                        v-model="
                                                            formData.contactTel
                                                        "
                                                        maxlength="11"
                                                    ></el-input>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="注册地址"
                                                    prop="registerAddInfo"
                                                >
                                                    <SelectAddr
                                                        v-model="
                                                            formData.registerAddInfo
                                                        "
                                                        @getLabel="getAddrLabel"
                                                        lazy
                                                        showCountry
                                                        style="width: 100%"
                                                    ></SelectAddr>
                                                    <!-- 详细地址 -->
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item
                                                    label="邮箱"
                                                >
                                                    <el-input
                                                        placeholder="请填写"
                                                        v-model="formData.email"
                                                    ></el-input>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="录入人">
                                                    {{ formData.founderName }}
                                                </el-form-item>
                                            </el-col>
                                            <el-col :span="12">
                                                <el-form-item label="录入机构">
                                                    {{ formData.orgName }}
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                        <el-row>
                                            <el-col :span="12">
                                                <el-form-item label="是否启用">
                                                    <el-switch
                                                        :width="60"
                                                        v-model="formData.state"
                                                        class="main-el-switch"
                                                        active-color="#13ce66"
                                                        inactive-color="#D2D2D2"
                                                        active-value="1"
                                                        inactive-value="0"
                                                        active-text="启用"
                                                        inactive-text="禁用"
                                                    >
                                                    </el-switch>
                                                </el-form-item>
                                            </el-col>
                                        </el-row>
                                    </el-form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 附件信息 -->
                    <div id="WarehouseCon" class="con">
                        <div class="tabs-title" id="accessory">附件信息</div>
                        <div class="e-table">
                            <div
                        style="margin-bottom: 20px"
                        class="errorMsg"
                        v-if="errorMsg.length > 0"
                    >
                        <span
                            style="display: block"
                            v-for="(item, index) in errorMsg"
                            :key="index"
                        >
                            {{ item }}
                        </span>
                    </div>
                            <AttachComp
                                :bucketName="bucketName"
                                :relationId="billid"
                                ref="accessory"
                            ></AttachComp>
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
        <div class="buttons">
            <span class="tip"
                ><span style="color: red; margin-right: 0">*</span
                >为必填项</span
            >
            <el-button
                type="primary"
                style="background: #2e61d7"
                @click="save()"
                >保存</el-button
            >
            <el-button @click="handleClose()">取消</el-button>
        </div>
    </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations } from 'vuex'
import SelectAddr from '@/components/common/addrComp'
import call from '@/api/OutsourcingartyAdmin/getAllType.js'
import Withtheunit from '@/api/OutsourcingartyAdmin/Withtheunit/Withtheunit.js'
import AttachComp from '@/components/common/attachIndex'
import { selectDataClient, throttle } from '@/utils/common'
let oldRouter = {} // 上一个页面来源
export default {
    components: {
        AttachComp,
        SelectAddr
    },
    data () {
        return {
            tabsName: 'baseInfo',
            bucketName: 'OutsourcingartyAdmin',
            userName: '',
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: ''
            },
            tableData: [],
            value: '',
            textarea: '',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            //表单数据
            formData: {
                businessUnitTypeKey: '', //单位类型名称
                businessUnitTypeValue: '', //单位类型id
                businessTypeKey: '', //业务类型名称
                businessTypeValue: '', //业务类型id
                creditCode: '', //统一社会信用代码
                businessUnitName: '', //单位名称
                contactName: '', //联系人
                contactTel: '', //联系电话
                registerAddInfo: '', //注册地址详情
                email: '', //邮箱
                founderName: '', //录入人
                founderId: '', //录入人id
                orgId: '', //录入机构id
                orgName: '', //录入机构名字
                state: '1' //启用【0：不启用，1启用】
            },
            unitList: [],
            businessList: [],
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [], //验证数组
            id: '',
            isSkip: false, //是否跳转
            winEvent: {}, //保存事件，跳转页面的时候，结束事件，优化性能
            isDisable: false, //如果被引用，单位类型，业务类型信用代码不可修改
            // 验证
            rules: {
                // 统一社会信用代码
                creditCode: [
                    {
                        required: true,
                        validator: this.creditCodeVolide,
                        trigger: ['blur', 'change']
                    }
                ],
                //单位类型
                businessUnitTypeValue: [
                    {
                        required: true,
                        message: '请选择单位类型',
                        trigger: 'change'
                    }
                ],
                //业务类型
                businessTypeValue: [
                    {
                        required: true,
                        message: '请选择业务类型',
                        trigger: 'change'
                    }
                ],
                //单位名称
                businessUnitName: [
                    {
                        required: true,
                        message: '请输入单位名称',
                        trigger: 'blur'
                    }
                ],
            }
        }
    },
    computed: {
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 480 - this.lastConHeight
        }
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData => {
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        }
    },
    created () {
        this.billid = this.$route.query.billid
        this.getBusinesseData()
        this.getBasicData() //进入页面就获取基本信息数据
    },
    // 进入页面之前拿到上个页面的来源
    beforeRouteEnter (to, from, next) {
        oldRouter = from
        next()
    },
    // 进入页面之后删掉
    beforeRouteLeave (to, from, next) {
        oldRouter = null
        next()
    },
    mounted () {
        // 如果是新增保存后点击“继续”跳转过来的，则定位到第2个tab
        if (oldRouter.path === '/subcontractorAdd') {
            // 将名字改为第二个详情
            this.tabsName = 'aptitude'
            this.$nextTick(() => {
                // 手动触发滚动事件
                this.onChangeTab({ name: 'aptitude' })
            })
        }
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()
        // 保存所有tabName
        const arr = ['baseInfo', 'accessory']
        this.tabArr = arr
        let $idsTop = []
        const onScroll = () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }
            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        }
        this.winEvent.onScroll = onScroll
        window.addEventListener('scroll', this.winEvent.onScroll)
        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        const onResize = () => {
            this.screenWidth = document.documentElement.clientWidth
            this.screenHeight = document.documentElement.clientHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        }
        this.winEvent.onResize = throttle(onResize, 500)
        window.addEventListener('resize', this.winEvent.onResize)
    },
    beforeDestroy () {
        window.removeEventListener('scroll', this.winEvent.onScroll)
        window.removeEventListener('resize', this.winEvent.onResize)
    },
    methods: {
        ...mapMutations(['setPopConfirm']),
        // 获取注册地址
        getAddrLabel (val) {
            this.formData.registerAdd = val
        },
        getBusinesseData () {
            call.getCredential('往来单位业务类型').then(res => {
                // 筛选掉内部结算
                this.businessList =  res.filter(item=>{
                    if(item.kvValue != 1) {
                        return item
                    }
                })
            })
            call.getCredential('往来单位类型').then(res => {
                this.unitList = res
            })
        },
        //获取基本信息数据
        async getBasicData () {
            let data = await Withtheunit.WiththeunitDetails({
                id: this.billid
            })
            data.state = data.state + ''
            // 如果单位类型为内部
            if (data.businessUnitTypeValue == '6') {
                this.businessList.map(newItem => {
                    if (newItem.kvValue != '6' && newItem.kvValue != '5') {
                        newItem.disabled = true
                    } else {
                        newItem.disabled = false
                    }
                })
            } else {
                this.businessList.map(newItem => {
                    if (newItem.kvValue == '6' || newItem.kvValue == '5') {
                        newItem.disabled = true
                    } else {
                        newItem.disabled = false
                    }
                })
            }
            data.isCite = '0'
            // 如果被引用，单位类型，业务类型信用代码不可修改
            if(data.isCite == '1') {
                this.isDisable = true
            }else{
                this.isDisable = false
            }
            this.formData =  data
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('evaluateCon')) {
                    const lastConHeight =
                        document.getElementById('evaluateCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    console.log('this.lastConHeight', this.lastConHeight)
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        //保存按钮
        async save () {
            this.errorList = []
            this.errorMsg = []
            this.$refs.formData.validate(async valid => {
                if (valid) {
                    // 验证附件必填
                    if (this.$refs.accessory.attachTableData.length > 0) {
                        this.isSend = true
                        let datas = JSON.parse(JSON.stringify(this.formData))
                        let data = await Withtheunit.WiththeunitUpdate(datas)
                        if (data) {
                            this.clientPop('suc', '保存成功')
                            this.$router.push('/Withtheunit')
                        } else {
                            this.clientPop('err', '保存失败')
                            this.setError('baseInfo')
                        }
                    } else {
                        this.setError('accessory')
                        this.errorMsg.push('附件未上传')
                    }
                } else {
                    this.setError('baseInfo')
                }
            })
        },
        handleFullScreen () {
            this.fullscreen = !this.fullscreen
        },
        //取消
        handleClose () {
            this.dialogVisible = false
            this.$router.push('./Withtheunit')
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.id
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },
        onChangeTab (e) {
            console.log('clickTabFlag: ', this.clickTabFlag)
            $.scrollTo(`#${e.name}`, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //单位类型选择
        businessUnitTypeChange (val) {
            this.formData.businessTypeValue = ''
            this.formData.businessTypeKey = ''
            this.unitList.map(item => {
                if (item.kvValue == val) {
                    this.formData.businessUnitTypeKey = item.kvKey
                }
            })
            // 如果单位类型为内部
            if (val == '6') {
                this.businessList.map(newItem => {
                    if (newItem.kvValue != '6' && newItem.kvValue != '5') {
                        newItem.disabled = true
                    } else {
                        newItem.disabled = false
                    }
                })
            } else {
                this.businessList.map(newItem => {
                    if (newItem.kvValue == '6' || newItem.kvValue == '5') {
                        newItem.disabled = true
                    } else {
                        newItem.disabled = false
                    }
                })
            }
        },
        //业务类型选择
        businessTypeKeyChange (val) {
            this.unitList.map(item => {
                if (item.kvValue == val) {
                    this.formData.businessTypeKey = item.kvKey
                }
            })
        },
        //设置错误标签
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        // 分包商弹窗选择详情
        onSelect () {
            if(!this.isDisable) {
                // 弹窗选择数据
                selectDataClient({
                    SelectServiceToken: '/hr/org/getAllOrgPage', // 客户端对应方法名
                    IsSingleMode: true, // 是否单选 true 单选 false 多选
                    SelectedIDs: [], // 已选中id
                    InitParamsStr: '',
                    Title: '往来单位选择'
                }).then(val => {
                    this.formData.businessUnitName = val[0].orgName
                    this.formData.creditCode = val[0].shortCode
                })
            }
        },
        creditCodeVolide (rule, value, callback) {
            const fn = () => {
                if (this.formData.businessUnitTypeValue !== '0') {
                    let creditCodeReg =
                        /[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}/
                    if (!value) {
                        return new Error('统一信用代码不能为空')
                    } else if (!creditCodeReg.test(value)) {
                        return new Error(
                            '请输入18位数字或者大写字母，但是字母不包括 I、O、Z、S、V'
                        )
                    } else {
                        return
                    }
                } else {
                    let creditCodeReg =
                        /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
                    if (!value) {
                        return new Error('身份证不能为空')
                    } else if (!creditCodeReg.test(value)) {
                        return new Error('请输入18位并正确的身份证号码')
                    } else {
                        return
                    }
                }
            }
            callback(fn())
        },
    }
}
</script>

<style lang="scss" scoped>
.buttons {
    left: 0;
}
.e-form {
    margin-bottom: 80px;
    padding: 0 20px;
    .tabs-title::before {
        content: '';
        height: 22px;
        width: 8px;
        border-radius: 40px;
        background-color: #2e61d7;
        display: block;
        position: absolute;
        left: 20px;
        margin-right: 20px;
    }
}

.e-table {
    background: #fff;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
    width: 6px; // 横向滚动条
    height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 5px;
}

.el-tab-pane {
    margin-left: -10px;
}

::v-deep .clearPadding .vxe-cell {
    padding: 0;
}
::v-deep .clearPaddingLeft .vxe-cell {
    padding-left: 0px;
}
::v-deep {
    .main-el-switch {
        position: relative;
        .el-switch__core {
            height: 24px;
            border-radius: 12px;
            &:after {
                left: 4px;
                top: 3px;
            }
        }
        &.el-switch {
            &.is-checked {
                .el-switch__core {
                    &:after {
                        margin-left: -20px;
                        left: 100%;
                    }
                }
            }
        }
        &.is-checked {
            .el-switch__label--left {
                opacity: 0;
            }
            .el-switch__label--right {
                opacity: 1;
            }
        }
        .el-switch__label {
            position: absolute;
            top: 0;
        }
        .el-switch__label--left {
            right: 0;
            color: #999;
            z-index: 1;
            margin-right: 8px;
        }
        .el-switch__label--right {
            left: 0;
            color: #fff;
            opacity: 0;
            margin-left: 8px;
        }
    }
}
</style>
